package com.example.cylooq.niceview.view.fragment

import android.support.v4.widget.SwipeRefreshLayout
import com.example.cylooq.niceview.R
import com.example.cylooq.niceview.adatper.HomeAdatper
import com.example.cylooq.niceview.model.bean.HomeBean
import com.example.cylooq.niceview.presenter.HomePresenter
import com.example.cylooq.niceview.presenter.contract.HomeContract
import com.example.cylooq.niceview.model.bean.HomeBean.IssueListBean.ItemListBean
import kotlinx.android.synthetic.main.home_fragment.*
import java.util.ArrayList
import java.util.regex.Pattern
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.Toast

import com.example.cylooq.niceview.utils.*

/**
 * Created by RuiChang on 2017/08/26.
 */
class HomeFragment : BaseFragment(), HomeContract.View, SwipeRefreshLayout.OnRefreshListener {
    var isRefresh: Boolean = false
    var homePresenter: HomePresenter? = null
    var itemListBean = ArrayList<ItemListBean>()
    var homeAdapter: HomeAdatper? = null
    var data: String? = null

    //TODO:加载时判断是否有缓存，是否有网络连接，阻止闪退
    //TODO:解决思路，加载一个fragment替换掉，然后从fragment设置点击事件从新回到这
    override fun setData(bean: HomeBean) {
        if (bean != null) {
            val regEx = "[^0-9]"
            val pattern = Pattern.compile(regEx)
            val patternMatcher = pattern.matcher(bean?.nextPageUrl)
            data = patternMatcher.replaceAll("")?.subSequence(1, patternMatcher.replaceAll("").length - 1).toString()
            //截取json的数据
            if (isRefresh) {
                isRefresh = false
                refreshLayout_home.isRefreshing = false
                if (itemListBean.size > 0) {
                    itemListBean.clear()
                }
            }
            bean?.issueList!!
                    .flatMap { it.itemList!! }
                    .filter { it.type.equals("video") }
                    .forEach { itemListBean.add(it) }
            homeAdapter?.notifyDataSetChanged()
        }
    }

    override fun getLayoutResources(): Int {
        return R.layout.home_fragment
    }

    override fun initView() {
        homePresenter = HomePresenter(context, this)
        recyclerView_home?.layoutManager = LinearLayoutManager(context)
        refreshLayout_home.setOnRefreshListener(this)
      /*  if (NetworkUtils.isNetConneted(context)) {*/
            //error_bg_home.visibility = View.INVISIBLE
            recyclerView_home.visibility = View.VISIBLE
            homePresenter?.start()
            homeAdapter = HomeAdatper(context, itemListBean)
            recyclerView_home.adapter = homeAdapter
            if (!NetworkUtils.isNetConneted(context)) {
                ToastMine(activity,"正在使用缓存数据，请联网后刷新",Toast.LENGTH_SHORT)
            }

            recyclerView_home.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    var layoutManagey: LinearLayoutManager = recyclerView?.layoutManager as LinearLayoutManager
                    var lastPositon = layoutManagey.findLastVisibleItemPosition()
                    if (NetworkUtils.isNetConneted(context)) {
                        if (newState == RecyclerView.SCROLL_STATE_IDLE && lastPositon == itemListBean.size - 1) {
                            homePresenter?.moreData(data)
                        }
                    } else {
                        //context.showToast("网络无连接，请稍后再试")
                        //activity.showToast("网络无连接，请稍后再试")
                        ToastMine(activity,"网络无链接，请稍后再试",Toast.LENGTH_SHORT)
                    }

                }
            })
       /* } else {
            error_bg_home.visibility = View.VISIBLE
            recyclerView_home.visibility = View.INVISIBLE
            error_bg_home.setOnClickListener(object : View.OnClickListener {
                override fun onClick(p0: View?) {
                    if (NetworkUtils.isNetConneted(context)) {
                        if (NetworkUtils.isNetConneted(context)) {
                            error_bg_home.visibility = View.INVISIBLE
                            recyclerView_home.visibility = View.VISIBLE
                            homePresenter?.start()
                            homeAdapter = HomeAdatper(context, itemListBean)
                            recyclerView_home.adapter = homeAdapter
                            if (!NetworkUtils.isNetConneted(context)) {
                                context.showToast("真正使用缓存数据，请联网后刷新")
                            }
                            recyclerView_home.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                                    super.onScrollStateChanged(recyclerView, newState)
                                    var layoutManagey: LinearLayoutManager = recyclerView?.layoutManager as LinearLayoutManager
                                    var lastPositon = layoutManagey.findLastVisibleItemPosition()
                                    if (NetworkUtils.isNetConneted(context)) {
                                        if (newState == RecyclerView.SCROLL_STATE_IDLE && lastPositon == itemListBean.size - 1) {
                                            homePresenter?.moreData(data)
                                        }
                                    } else {
                                        context.showToast("网络无连接，请稍后再试")
                                    }
                                }
                            })
                        }
                    }
                }
            })
        }*/


    }

    override fun onRefresh() {
        if (NetworkUtils.isNetConneted(context)) {
            if (!isRefresh) {
                isRefresh = true
                homePresenter?.start()
            }
        } else {
            ToastMine(activity,"网络无链接，请稍后再试",Toast.LENGTH_SHORT)
            isRefresh = false
            refreshLayout_home.isRefreshing = false
        }
    }

}